import React, { useRef, memo, useState, useEffect } from 'react';
import { Row, Col, Form, Button, MessagePlugin, Select, Input } from 'tdesign-react';
import { FormInstanceFunctions, SubmitContext } from 'tdesign-react/es/form/type';
import { useLocation, useNavigate } from 'react-router-dom';
import RegisterDialog from './RegisterDialog';
const { FormItem } = Form;

export type FormValueType = {
  searchText?: string;
  role?: string;
  sortBy?: string;
  sortOrder?: string;
};

export type SearchFormProps = {
  onCancel: () => void;
  onSubmit: (values: FormValueType) => Promise<void>;
};

const SearchForm: React.FC<SearchFormProps> = (props) => {
  const formRef = useRef<FormInstanceFunctions>();
  const location = useLocation();
  const navigate = useNavigate();
  const [registerVisible, setRegisterVisible] = useState(false);

  // 解析 query 参数
  function getQueryParams() {
    const params = new URLSearchParams(location.search);
    return {
      searchText: params.get('searchText') || '',
      role: params.get('role') || '',
      sortBy: params.get('sortBy') || '',
      sortOrder: params.get('sortOrder') || '',
    };
  }

  // 初始化时回显 query 到表单
  useEffect(() => {
    const query = getQueryParams();
    formRef.current?.setFieldsValue?.(query);
  }, [location.search]);

  // 提交时同步 query 到路由
  const onSubmit = (e: SubmitContext) => {
    if (e.validateResult === true) {
      const queryValue = formRef?.current?.getFieldsValue?.(true) || {};
      // 构建 query 字符串
      const params = new URLSearchParams();
      Object.entries(queryValue).forEach(([key, value]) => {
        if (value) params.set(key, value as string);
      });
      navigate({ search: params.toString() }, { replace: true });
      props.onSubmit(queryValue as FormValueType);
      MessagePlugin.success('查询成功');
    }
  };

  // 重置时同步清空 query
  const onReset = () => {
    props.onCancel();
    navigate({ search: '' }, { replace: true });
    MessagePlugin.success('重置成功');
  };

  return (
    <div className='list-common-table-query'>
      <Form ref={formRef} onSubmit={onSubmit} onReset={onReset} labelWidth={80} colon>
        <Row>
          <Col flex='1'>
            <Row gutter={[12, 12]}>
              <Col span={4} xs={12} sm={6} xl={3}>
                <FormItem label='搜索' name='searchText'>
                  <Input placeholder='请输入学号/姓名' style={{ width: '100%' }} />
                </FormItem>
              </Col>
              <Col span={4} xs={12} sm={6} xl={3}>
                <FormItem label='角色' name='role'>
                  <Select options={[
                    { label: '全部', value: '' },
                    { label: '学生', value: 'student' },
                    { label: '教师', value: 'teacher' },
                    { label: '管理员', value: 'admin' },
                  ]} placeholder='请选择角色' />
                </FormItem>
              </Col>
              <Col span={4} xs={12} sm={6} xl={3}>
                <FormItem label='排序依据' name='sortBy'>
                  <Select options={[
                    { label: '学号', value: 'studentId' },
                    { label: '角色', value: 'role' },
                  ]} placeholder='请选择排序依据' />
                </FormItem>
              </Col>
              <Col span={4} xs={12} sm={6} xl={3}>
                <FormItem label='排序方式' name='sortOrder'>
                  <Select options={[
                    { label: '升序', value: 'ASC' },
                    { label: '降序', value: 'DESC' },
                  ]} placeholder='请选择排序方式' />
                </FormItem>
              </Col>
            </Row>
          </Col>
          <Col flex='280px'>
            <Button theme='primary' type='submit' style={{ margin: '0px 20px' }}>
              查询
            </Button>
            <Button type='reset' variant='base' theme='default' style={{ position: "relative", margin: '0px 20px 0 0' }}>
              重置
            </Button>
            <Button theme='primary' onClick={() => setRegisterVisible(true)}>
              新建用户
            </Button>
          </Col>
        </Row>
      </Form>

      <RegisterDialog
        visible={registerVisible}
        onClose={() => setRegisterVisible(false)}
        onSuccess={() => {
          setRegisterVisible(false);
          // 刷新列表
          const currentQuery = formRef.current?.getFieldsValue?.(true) || {};
          props.onSubmit(currentQuery as FormValueType);
        }}
      />
    </div>
  );
};

export default memo(SearchForm);
